import React, {FC, useContext, useMemo, useState} from 'react';
import "./index.less";
import * as API from "@/services";
import {unsubscribeJournal} from "@/services";
import {useRequest} from "ahooks";
import {Button, Descriptions, Divider, message, Space, Table} from "antd";
import {FormattedMessage} from "@@/exports";
import {correspVal} from "@/utils/biz";
import {HxConfigContext} from "@/layouts/HxConfigContext";
import {KfFloatingContext, KfModal, useBackendEnum} from "kf-web-library";
import numeral from "numeral";
import {useIntl} from "umi";
import {downloadJournalPeriodPdf} from "@/utils/download";
import useAuthedCheck from "@/components/hooks/UseAuthedCheck";
import {LoadingOutlined} from "@ant-design/icons";
import classNames from "classnames";


const SubscriptionJournalPeriodPdfAction: FC<{
  period: API.FrontJournalPeriod
}> = (props) => {
  const {isZhCN} = useContext(HxConfigContext);
  const authedCheck = useAuthedCheck();
  const [downloading, setDownloading] = useState(false);
  const {period} = props;

  return (
    <a
      className={classNames({"hx-downloading": downloading})}
      onClick={(e) => {
        e.preventDefault();
        authedCheck(async () => {
          if (downloading) {
            return;
          }
          setDownloading(true);
          await downloadJournalPeriodPdf(period, isZhCN);
          setDownloading(false);
        })
      }}
    >
      {downloading && <LoadingOutlined/>}
      <FormattedMessage id="text.download"/>
    </a>
  )
};

interface SubscriptionDetailProps {
  subscriptionId: API.EntityId;
}

const SubscriptionDetail: FC<SubscriptionDetailProps> = (props) => {
  const {subscriptionId} = props;
  const {isZhCN} = useContext(HxConfigContext);
  const intl = useIntl();
  const authedCheck = useAuthedCheck();
  const [downloading, setDownloading] = useState(false);

  const kfFloatingContext = useContext(KfFloatingContext)
  const {enumDict, enumTypeDict, getBackendEnum} = useBackendEnum();
  const subscribesReq = useRequest((p) => API.queryFrontJournalSubscribe(subscriptionId))

  const record = subscribesReq.data?.data;
  const journalName = correspVal(isZhCN, record?.journal?.journalNameCn, record?.journal?.journalNameEn);

  //是否允许退订(退款)
  const allowUnsubscribe = useMemo(() => {
    if (record?.timeType !== "FUTURE") {
      return false;
    }
    if (record?.order?.status !== "PAID") {
      return false;
    }
    if (record.periodCount >= record.shippingCount) {
      return false;
    }
    return true;
  }, [record]);

  return (
    <div className={"subscription-detail-container"}>
      <Descriptions title={<FormattedMessage id="mall.SubscriptionItems"/>}
                    column={1}
                    size={"middle"}>
        <Descriptions.Item label={<FormattedMessage id="mall.SubscriptionDate"/>}>
          {record?.subscribeDate}
        </Descriptions.Item>
        <Descriptions.Item label={<FormattedMessage id="text.subscribe-status"/>}>
          {getBackendEnum("SubscribeStatus", record?.status)?.i18EnumDesc}
        </Descriptions.Item>
        <Descriptions.Item label={<FormattedMessage id="mall.SubscriptionJournalName"/>}>
          {journalName}
        </Descriptions.Item>
        <Descriptions.Item label={<FormattedMessage id="mall.SubscriptionCarrier"/>}>
          {getBackendEnum("SubscribeDisplayType", record?.displayType)?.i18EnumDesc}
        </Descriptions.Item>
        <Descriptions.Item label={<FormattedMessage id="mall.SubscriptionPeriod"/>}>
          {getBackendEnum("SubscribeTimeType", record?.timeType)?.i18EnumDesc}
        </Descriptions.Item>
        <Descriptions.Item label={<FormattedMessage id="mall.SubscriptionSelect"/>}
                           styles={{
                             content: {
                               width: "100%", display: "block"
                             }
                           }}
        >
          <div>
            <FormattedMessage id="journal.period-info.aggregate-by-subscribed-issue" values={{
              total: record?.periodCount || 0,
              deliveredCount: record?.periodListCount || 0,
            }}/>
          </div>
          <div>
            <Table
              style={{width: "100%", marginTop: 12}}
              bordered={true}
              pagination={false}
              size={"small"}
              columns={[
                {
                  title: <FormattedMessage id="journal.meta.Year"/>,
                  width: 100,
                  dataIndex: "year"
                },
                {
                  title: <FormattedMessage id="journal.meta.Volume"/>,
                  width: 100,
                  dataIndex: "volume"
                },
                {
                  title: <FormattedMessage id="journal.meta.Issue"/>,
                  dataIndex: "period"
                },
                {
                  title: <FormattedMessage id="text.action"/>,
                  width: 200,
                  dataIndex: "option",
                  render: (_, record) => {
                    return (
                      <Space size={0} split={<Divider type="vertical"/>} className={"subscription-select-item-action-space"}>
                        <SubscriptionJournalPeriodPdfAction period={record}/>
                        <a
                          onClick={() => {

                          }}
                        >
                          <FormattedMessage id="text.resend"/>
                        </a>
                      </Space>
                    )
                  }
                },
              ]}
              dataSource={record?.periodList || []}
            />
          </div>
        </Descriptions.Item>
      </Descriptions>

      <Descriptions title={<FormattedMessage id="mall.SubscriptionOrderSummary"/>}
                    column={1}
                    style={{marginTop: 32}}
                    size={"middle"}>
        <Descriptions.Item label={<FormattedMessage id="mall.SubscriptionTotalOrderAmount"/>}>
          ￥{numeral((record?.order?.totalPrice || 0) / 100).format('0.00')}
        </Descriptions.Item>
        <Descriptions.Item label={<FormattedMessage id="text.pay-status"/>}>
          {getBackendEnum("PayOrderStatus", record?.order?.status)?.i18EnumDesc}
        </Descriptions.Item>
      </Descriptions>

      <div style={{marginTop: 48}}>
        <Space>
          {
            allowUnsubscribe && (
              <Button type="primary" onClick={() => {
                KfModal.confirm2(
                  intl.formatMessage({id: "text.unsubscribe"}),
                  intl.formatMessage({id: "mall.unsubscribe_confirm_title"}),
                  () => {
                    unsubscribeJournal(record!.id).then((resp) => {
                      if (resp.flag) {
                        message.success("取消订阅成功");
                        subscribesReq.refresh();
                      }
                    })
                  },
                  () => {
                  },
                  {
                    okText: intl.formatMessage({id: "text.confirm"}),
                    cancelText: intl.formatMessage({id: "text.cancel"}),
                  }
                )
              }}>
                <FormattedMessage id="text.unsubscribe"/>
              </Button>
            )
          }

          <Button type="default" onClick={() => {
            kfFloatingContext?.closeWrapFloating?.(false);
          }}>
            <FormattedMessage id="text.close"/>
          </Button>
        </Space>
      </div>
    </div>
  );
};


export default SubscriptionDetail;
